#include <stdio.h>
#include "pthread.h"
#include <unistd.h>
/* linux 多线程同步-----条件变量 */
/* 
    变量类型  pthread_cond_t
    初始化
        pthread_cond_t cond =  PTHREAD_COND_INITIALIZER  //静态初始化 常量赋值
        int pthread_cond_init(pthread_cond_t *cond,pthread_condattr_t *condattr) //动态初始化 condattr 一般为NULL
    销毁
        pthread_cond_destory(pthread_cond_t *cond)
    条件等待
        pthread_cond_wait(pthread_cond_t *cond,pthread_mutex *mutex);//永久等待
        pthread_cond_timewait(pthread_cond_t *cond,pthread_mutex *mutex,const struct timespec *abstime)//超时等待
        使用实例：条件变量在使用是必须和互斥量一同使用，使用前必须加锁。wait内部解锁，等待线程释放后自动获取锁，然后解锁
            pthread_mutex_lock(&mutex)
            pthread_cond_wait(&cond,&mutex);
            pthread_mutex_unlock(&mutex)
    唤醒
        pthread_cond_signal(pthread_cond_t *cond);//唤醒条件等待的线程。存在多个等待线程时按照入队顺序唤醒其中一个线程，
        pthread_cond_broadcast(pthread_cond_t *cond)//唤醒所有条件等待的线程。
        使用实例：唤醒操作是原子操作，必须加锁
            pthread_mutex_lock(&mutex)
            pthread_cond_signal(&cond)
            pthread_mutex_unlock(&mutex)  
*/

/* 相关变量 */
struct MyStruct
{
    pthread_cond_t cond;
    pthread_mutex_t mutex;
};
struct MyStruct CondTask;
void *WaitTask(void *data)
{
    pthread_detach(pthread_self());//线程分离
    int count = 0;
    while (1)
    {
        pthread_mutex_lock(&CondTask.mutex);
        pthread_cond_wait(&CondTask.cond, &CondTask.mutex);
        pthread_mutex_unlock(&CondTask.mutex);
        count++;
        printf("count = %d \n", count);
    }
    pthread_exit(NULL);
}
void *SignalTask(void *data)
{
    char readbuff[50];
    pthread_detach(pthread_self());//线程分离
    while (1)
    {
        printf("please input stringn\n");
        scanf("%s",readbuff);
        pthread_mutex_lock(&CondTask.mutex);
        pthread_cond_signal(&CondTask.cond);
        pthread_mutex_unlock(&CondTask.mutex);
    }
    pthread_exit(NULL);
}
int main(int argc, char const *argv[])
{
    /* code */
    /* 创建两个线程 */
    int thread_ret = 0;
    pthread_t thread_tid1, thread_tid2;

    thread_ret = pthread_create(&thread_tid1, NULL, WaitTask, NULL);
    if (thread_ret == -1)
    {
        perror("pthread_create\n");
    }
    thread_ret = pthread_create(&thread_tid2, NULL, SignalTask, NULL);
    if (thread_ret == -1)
    {
        perror("pthread_create\n");
    }
    sleep(2);
    pthread_exit(NULL);
    return 0;
}
